﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace BangkokSteel
{
    public partial class frmSupplier : Form, MainFormListener
    {

        private TabControl mainTab;
        private MySqlConnection conn = null;
        private MySqlDataAdapter adapter = null;        
        private string MODE = "";

        public frmSupplier(TabControl mainTab)
        {
            this.mainTab = mainTab;
            InitializeComponent();
        }

        #region Form Event

        private void frmSupplier_Load(object sender, EventArgs e)
        {
            conn = new MySqlConnection(BangkokSteel.Properties.Settings.Default.bangkoksteelConnectionString);

            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
            }

            conn.Open();

            string strSQL = " SELECT supplier_id,name,owner_name,address,address_map";
            strSQL = strSQL + " ,(SELECT name FROM supplier_type WHERE ID = supplier.supplier_type_id limit 1) as supplier_type_id";
            strSQL = strSQL + " ,credit_limit";
            strSQL = strSQL + " ,(SELECT name FROM payment_term WHERE ID = supplier.payment_term_id limit 1) as payment_term_id";
            strSQL = strSQL + " ,(SELECT name FROM received_condition WHERE ID = supplier.received_condition_id limit 1) as received_condition_id";
            strSQL = strSQL + " ,(SELECT name FROM vat WHERE ID = supplier.vat_id limit 1) as vat_id";
            strSQL = strSQL + " FROM  supplier";              

            adapter = new MySqlDataAdapter(strSQL, conn);
            adapter.Fill(dataSet1, "supplier");

            dataGridView1.DataSource = dataSet1.Tables["supplier"];

            //SET Combobox
            SetCbo();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.mainTab.TabPages.Remove(this.mainTab.SelectedTab);
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            EnableOrDisableMainPage(false);

            MODE = "ADD";

            ClearFields();

            panel1.Visible = true;
            txtId.Focus();
            txtId.Select();

            txtId.Enabled = true;
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count > 0 && dataGridView1.SelectedRows.Count > 0)
            {
                EnableOrDisableMainPage(false);

                DataGridViewRow row = dataGridView1.SelectedRows[0];

                MODE = "EDIT";

                txtId.Text = row.Cells["supplier_id"].Value.ToString();
                txtName.Text = row.Cells["name"].Value.ToString();
                txtOwner.Text = row.Cells["owner_name"].Value.ToString();
                txtAddress.Text = row.Cells["address"].Value.ToString();
                cboSupplierType.SelectedItem = row.Cells["supplier_type_id"].Value.ToString();
                txtCredit.Text = row.Cells["credit_limit"].Value.ToString();
                cboPaymentTerm.SelectedItem = row.Cells["payment_term_id"].Value.ToString();
                cboReceiveCon.SelectedItem = row.Cells["received_condition_id"].Value.ToString();
                cboVat.SelectedItem = row.Cells["vat_id"].Value.ToString();

                panel1.Visible = true;

                txtName.Focus();
                txtName.SelectAll();

                txtId.Enabled = false;
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count > 0 && dataGridView1.SelectedRows.Count > 0)
            {
                if (DialogResult.Yes == MessageBox.Show("คุณต้องการลบข้อมูลนี้ใช่หรือไม่", "คำยืนยัน", MessageBoxButtons.YesNo, MessageBoxIcon.Question))
                {
                    DataGridViewRow row = dataGridView1.SelectedRows[0];

                    string sql = "DELETE FROM `supplier` WHERE (`supplier_id` = @Original_id)";

                    MySqlCommand cmd = new MySqlCommand(sql, conn);
                    cmd.Parameters.Clear();
                    cmd.Parameters.Add("@Original_id", MySqlDbType.String).Value = row.Cells["supplier_id"].Value;

                    cmd.ExecuteNonQuery();

                    MessageBox.Show("ลบข้อมูลเรียบร้อยแล้ว");
                    MODE = "";

                    // Refresh for New Data
                    dataSet1.Tables["supplier"].Clear();
                    adapter.Fill(dataSet1, "supplier");
                }
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                if (Validation())
                {
                    MySqlCommandBuilder builder = new MySqlCommandBuilder(adapter);

                    if ("ADD".Equals(MODE))
                    {
                        MySqlCommand cmd = (MySqlCommand)builder.GetInsertCommand(true);

                        cmd.Parameters.Clear();
                        cmd.Parameters.Add("@supplier_id", MySqlDbType.VarChar).Value = txtId.Text;
                        cmd.Parameters.Add("@name", MySqlDbType.VarChar).Value = txtName.Text;
                        cmd.Parameters.Add("@owner_name", MySqlDbType.VarChar).Value = txtOwner.Text;
                        cmd.Parameters.Add("@address", MySqlDbType.VarChar).Value = txtAddress.Text;
                        cmd.Parameters.Add("@address_map", MySqlDbType.Blob).Value = null;
                        cmd.Parameters.Add("@supplier_type_id", MySqlDbType.Int32).Value = cboSupplierType.SelectedValue;
                        cmd.Parameters.Add("@credit_limit", MySqlDbType.Double).Value = txtCredit.Text;
                        cmd.Parameters.Add("@payment_term_id", MySqlDbType.Int32).Value = cboPaymentTerm.SelectedValue;
                        cmd.Parameters.Add("@received_condition_id", MySqlDbType.Int32).Value = cboReceiveCon.SelectedValue;
                        cmd.Parameters.Add("@vat_id", MySqlDbType.Int32).Value = cboVat.SelectedValue;

                        //int affectedRow = cmd.ExecuteNonQuery();
                        cmd.ExecuteNonQuery();

                        MessageBox.Show("เพิ่มข้อมูลเรียบร้อยแล้ว");
                        ClearFields();

                        txtName.Focus();
                        txtName.SelectAll();

                    }
                    else if ("EDIT".Equals(MODE))
                    {
                        string sql = @"UPDATE `supplier` SET `name` = @name, `owner_name` = @owner_name ";
                        sql = sql + " , `address` = @address , `address_map` = @address_map , `supplier_type_id` = @supplier_type_id";
                        sql = sql + " , `credit_limit` = @credit_limit , `payment_term_id` = @payment_term_id";
                        sql = sql + " , `received_condition_id` = @received_condition_id , `vat_id` = @vat_id";
                        sql = sql + " WHERE (`supplier_id` = @Original_id)";

                        MySqlCommand cmd = new MySqlCommand(sql, conn);
                        cmd.Parameters.Add("@name", MySqlDbType.VarChar).Value = txtName.Text;
                        cmd.Parameters.Add("@owner_name", MySqlDbType.VarChar).Value = txtOwner.Text;
                        cmd.Parameters.Add("@address", MySqlDbType.VarChar).Value = txtAddress.Text;
                        cmd.Parameters.Add("@address_map", MySqlDbType.Blob).Value = null;
                        cmd.Parameters.Add("@supplier_type_id", MySqlDbType.Int32).Value = cboSupplierType.SelectedValue;
                        cmd.Parameters.Add("@credit_limit", MySqlDbType.Double).Value = txtCredit.Text;
                        cmd.Parameters.Add("@payment_term_id", MySqlDbType.Int32).Value = cboPaymentTerm.SelectedValue;
                        cmd.Parameters.Add("@received_condition_id", MySqlDbType.Int32).Value = cboReceiveCon.SelectedValue;
                        cmd.Parameters.Add("@vat_id", MySqlDbType.Int32).Value = cboVat.SelectedValue;
                        cmd.Parameters.Add("@Original_id", MySqlDbType.VarChar).Value = txtId.Text;

                        cmd.ExecuteNonQuery();

                        MessageBox.Show("แก้ไขข้อมูลเรียบร้อยแล้ว");

                        panel1.Visible = false;
                        EnableOrDisableMainPage(true);
                        ClearFields();

                        MODE = "";
                    }
                    // Refresh for New Data
                    dataSet1.Tables["supplier"].Clear();
                    adapter.Fill(dataSet1, "supplier");
                }
            }
            catch (FormatException ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            EnableOrDisableMainPage(true);

            panel1.Visible = false;
            MODE = "";
            ClearFields();
        }

        private void frmSupplier_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Escape:
                    {
                        if (panel1.Visible)
                        {
                            btnCancel_Click(null, null);
                        }
                        else
                        {
                            btnClose_Click(null, null);
                        }
                    }
                    break;
                case Keys.F2:
                    {
                        if (panel1.Visible)
                        {
                            btnOK_Click(null, null);
                        }
                        else
                        {
                            btnAdd_Click(null, null);
                        }
                    }
                    break;

                case Keys.F3:
                    {
                        //if (panel1.Visible)
                        //{
                        //    btnOK_Click(null, null);
                        //}
                        //else
                        //{
                        //    btnEdit_Click(null, null);
                        //}
                        btnEdit_Click(null, null);
                    }
                    break;

                case Keys.F4:
                    {
                        btnDelete_Click(null, null);
                    }
                    break;
            }
        }

        #endregion

        #region Function

        private void EnableOrDisableMainPage(bool isEnable)
        {
            btnAdd.Enabled = isEnable;
            btnEdit.Enabled = isEnable;
            btnDelete.Enabled = isEnable;
            btnClose.Enabled = isEnable;
            dataGridView1.Enabled = isEnable;
        }

        private void ClearFields()
        {
            txtId.Text = "";
            txtName.Text = "";
            txtOwner.Text = "";
            txtAddress.Text = "";
            cboSupplierType.SelectedIndex = 0;
            txtCredit.Text = "";
            cboPaymentTerm.SelectedIndex = 0;
            cboReceiveCon.SelectedIndex = 0;
            cboVat.SelectedIndex = 0;
        }

        private void SetCbo()
        {
            //Supplier Type
            MySqlDataAdapter adapter2 = new MySqlDataAdapter("SELECT * FROM supplier_type", conn);
            adapter2.Fill(dataSet1, "supplier_type");
            cboSupplierType.DataSource = dataSet1.Tables["supplier_type"];
            cboSupplierType.DisplayMember = "name";
            cboSupplierType.ValueMember = "id";

            //Payment Term
            MySqlDataAdapter adapter3 = new MySqlDataAdapter("SELECT * FROM payment_term", conn);
            adapter3.Fill(dataSet1, "payment_term");
            cboPaymentTerm.DataSource = dataSet1.Tables["payment_term"];
            cboPaymentTerm.DisplayMember = "name";
            cboPaymentTerm.ValueMember = "id";

            //Receive Condition
            MySqlDataAdapter adapter4 = new MySqlDataAdapter("SELECT * FROM received_condition", conn);
            adapter4.Fill(dataSet1, "received_condition");
            cboReceiveCon.DataSource = dataSet1.Tables["received_condition"];
            cboReceiveCon.DisplayMember = "name";
            cboReceiveCon.ValueMember = "id";

            //VAT
            MySqlDataAdapter adapter5 = new MySqlDataAdapter("SELECT * FROM vat", conn);
            adapter5.Fill(dataSet1, "vat");
            cboVat.DataSource = dataSet1.Tables["vat"];
            cboVat.DisplayMember = "name";
            cboVat.ValueMember = "id";
        }

        private bool Validation()
        {

            if (txtId.Text.Trim().Length == 0)
            {
                MessageBox.Show("กรุณาเลือกใส่รหัสให้เรียบร้อย");

                txtId.Focus();
                txtId.SelectAll();

                return false;
            }

            if (txtName.Text.Trim().Length == 0)
            {
                MessageBox.Show("กรุณาเลือกใส่ชื่อให้เรียบร้อย");

                txtName.Focus();
                txtName.SelectAll();

                return false;
            }

            if (txtOwner.Text.Trim().Length == 0)
            {
                MessageBox.Show("กรุณาเลือกใส่ชื่อเจ้าของให้เรียบร้อย");

                txtOwner.Focus();
                txtOwner.SelectAll();

                return false;
            }

            if (txtAddress.Text.Trim().Length == 0)
            {
                MessageBox.Show("กรุณาเลือกใส่ที่อยู่ให้เรียบร้อย");

                txtAddress.Focus();
                txtAddress.SelectAll();

                return false;
            }

            if (cboSupplierType.SelectedValue == null)
            {
                MessageBox.Show("กรุณาเลือก Supplier Type ให้เรียบร้อย");
                return false;
            }

            if (txtCredit.Text.Trim().Length == 0)
            {
                MessageBox.Show("กรุณาเลือกใส่เครดิตให้เรียบร้อย");

                txtCredit.Focus();
                txtCredit.SelectAll();

                return false;
            }

            if (cboPaymentTerm.SelectedValue == null)
            {
                MessageBox.Show("กรุณาเลือกกลุ่มการจ่ายให้เรียบร้อย");
                return false;
            }

            if (cboReceiveCon.SelectedValue == null)
            {
                MessageBox.Show("กรุณาเลือกกลุ่มเงื่อนไขการรับสินค้าให้เรียบร้อย");
                return false;
            }

            if (cboVat.SelectedValue == null)
            {
                MessageBox.Show("กรุณาเลือก VAT ให้เรียบร้อย");
                return false;
            }

            //=========================================================================================================
            DataSet ds = new DataSet();
            conn = new MySqlConnection(BangkokSteel.Properties.Settings.Default.bangkoksteelConnectionString);

            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
            }

            conn.Open();

            adapter = new MySqlDataAdapter("SELECT * FROM supplier WHERE supplier_id = '" + txtId.Text + "'", conn);
            adapter.Fill(ds);

            if (!(ds.Tables[0] == null || ds.Tables[0].Rows.Count == 0))
            {
                MessageBox.Show("มีรหัสนี้อยู่ในระบบเรียบร้อย");
                return false;
            }

            //=========================================================================================================

            return true;
        }

        #endregion

        #region Interface

        void MainFormListener.onMainFormClose()
        {
            // TODO
        }

        public void onTabPageAdded()
        {
            // TODO
        }

        #endregion

    }
}
